package com.gitee.cui.es;

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;

/**
 * ES创建文档操作
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022-04-05 15:56
 **/
public class ESDocCreate {

	public static void main(String[] args) throws IOException {
		RestHighLevelClient client = new RestHighLevelClient(
				RestClient.builder(new HttpHost("localhost", 9200, "http")));

		// 创建文档
		IndexRequest indexRequest = new IndexRequest("user");
		indexRequest.id("1001");

		User user = new User();
		user.setName("张三");
		user.setAge(32);
		user.setSex("男");
		ObjectMapper objectMapper = new ObjectMapper();
		String userJson = objectMapper.writeValueAsString(user);
		indexRequest.source(userJson, XContentType.JSON);

		IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
		System.out.println(response.getResult());
		
		client.close();
	}
}
